from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeCheckSerialzier(serializers.Serializer):
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(min_length=4, max_length=4)

    # 自定义校验
    def validate(self, attrs):
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        mobile = self.context['view'].kwargs['mobile']

        # 凭借这image_code_id取出redis中的图片验证码
        redis_conn = get_redis_connection('verify_codes')
        real_code = redis_conn.get('img_%s' % image_code_id)
        if not real_code:
            raise serializers.ValidationError('无效的图片验证码')

        real_code = real_code.decode()

        # 删除图片验证ma
        redis_conn.delete('img_%s' % image_code_id)

        # 验证码进行对比
        if text.lower() != real_code.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 验证短信是否在要求时间内以及发送
        mobile_data = redis_conn.get('send_flag_%s' % mobile)  # 按照手机号取出redis中储存的发送短信动作
        if mobile_data:
            raise serializers.ValidationError('发送短信过于频繁')

        return attrs
